﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SlamCms.Common.Security
{
	public static class EncryptionService
	{
		private const string defaultPassPhrase = "oia2uer(*&#4302";

		public static string Encrypt(string stringToEncrypt)
		{
			return new CryptoPrivateKeyUtil(defaultPassPhrase).Encrypt(stringToEncrypt);
		}

		public static string Encrypt(string stringToEncrypt, string passPhrase)
		{
			return new CryptoPrivateKeyUtil(passPhrase).Encrypt(stringToEncrypt);
		}

		public static string EncryptWithTimestamp(string stringToEncrypt)
		{
			return new CryptoPrivateKeyUtil(defaultPassPhrase).Encrypt(string.Format("{0}|{1}", stringToEncrypt, DateTime.UtcNow));
		}

		public static string EncryptWithTimestamp(string stringToEncrypt, string passPhrase)
		{
			return new CryptoPrivateKeyUtil(passPhrase).Encrypt(string.Format("{0}|{1}", stringToEncrypt, DateTime.UtcNow));
		}

		public static string Decrypt(string stringToDecrypt)
		{
			try
			{
				return new CryptoPrivateKeyUtil(defaultPassPhrase).Decrypt(stringToDecrypt);
			}
			catch
			{
				//todo: log error/notification
				return "";
			}

		}

		public static string Decrypt(string stringToDecrypt, string passPhrase)
		{
			try
			{
				return new CryptoPrivateKeyUtil(passPhrase).Decrypt(stringToDecrypt);
			}
			catch
			{
				//todo: log error/notification
				return "";
			}
		}

		public static string DecryptWithExpiration(string stringToDecrypt, TimeSpan maximumValidAge)
		{
			try
			{
				var decryptedString = new CryptoPrivateKeyUtil(defaultPassPhrase).Decrypt(stringToDecrypt).Split('|');
				if (DateTime.Parse(decryptedString[1]) > DateTime.UtcNow.Add(-maximumValidAge))
					return decryptedString[0];
			}
			catch
			{
				//todo: log error/notification
			}
			return "";
		}

		public static string DecryptWithExpiration(string stringToDecrypt, string passPhrase, TimeSpan maximumValidAge)
		{
			try
			{
				var decryptedString = new CryptoPrivateKeyUtil(passPhrase).Decrypt(stringToDecrypt).Split('|');
				if (DateTime.Parse(decryptedString[1]) > DateTime.UtcNow.Add(-maximumValidAge))
					return decryptedString[0];
			}
			catch
			{
				//todo: log error/notification
			}
			return "";
		}
	}
}
